import os
import json
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.db import transaction
from psychology_learning.models import LearningResource  # 请替换为你的实际app名称


class Command(BaseCommand):
    help = '从JSON文件导入学习资源数据到数据库'

    def add_arguments(self, parser):
        parser.add_argument(
            '--clear',
            action='store_true',
            help='导入前清空现有数据',
        )
        parser.add_argument(
            '--json-dir',
            type=str,
            default='.',
            help='JSON文件所在目录路径（默认为项目根目录）',
        )

    def handle(self, *args, **options):
        """主要处理逻辑"""

        # 检查现有数据
        if LearningResource.objects.exists():
            if options['clear']:
                self.stdout.write(
                    self.style.WARNING('正在清空现有数据...')
                )
                LearningResource.objects.all().delete()
                self.stdout.write(
                    self.style.SUCCESS('现有数据已清空')
                )
            else:
                raise CommandError(
                    '数据库中已有数据。使用 --clear 参数来清空现有数据，或手动清空数据库。'
                )

        # JSON文件列表
        json_files = [
            '成长的烦恼.json',
            '青春期男孩.json',
            '青春期女孩.json'
        ]

        # 获取JSON文件目录
        all_json_files = [
            os.path.join(settings.BASE_DIR, "static", "knowledge", i)
            for i in json_files
        ]


        imported_count = 0

        # 使用数据库事务确保数据完整性
        try:
            with transaction.atomic():
                for file_path in all_json_files:

                    if not os.path.exists(file_path):
                        self.stdout.write(
                            self.style.WARNING(f'文件不存在，跳过: {file_path}')
                        )
                        continue

                    self.stdout.write(f'正在导入: {file_path}')

                    # 读取JSON文件
                    try:
                        with open(file_path, 'r', encoding='utf-8') as f:
                            data = json.load(f)
                    except (json.JSONDecodeError, UnicodeDecodeError) as e:
                        self.stdout.write(
                            self.style.ERROR(f'读取文件失败 {file_path}: {str(e)}')
                        )
                        continue

                    # 处理每条数据
                    file_imported_count = 0
                    for item in data:
                        try:
                            resource = self.create_learning_resource(item)
                            resource.save()
                            imported_count += 1
                            file_imported_count += 1
                        except Exception as e:
                            self.stdout.write(
                                self.style.ERROR(
                                    f'导入数据失败 (标题: {item.get("title", "未知")}): {str(e)}'
                                )
                            )
                            continue

                    self.stdout.write(
                        self.style.SUCCESS(
                            f'从 {file_path} 成功导入 {file_imported_count} 条数据'
                        )
                    )

        except Exception as e:
            raise CommandError(f'导入过程中发生错误: {str(e)}')

        # 输出总结
        self.stdout.write('')
        self.stdout.write(
            self.style.SUCCESS(
                f'✅ 数据导入完成！总共成功导入 {imported_count} 条数据'
            )
        )

        # 验证导入结果
        total_records = LearningResource.objects.count()
        self.stdout.write(f'数据库中现有记录总数: {total_records}')

    def create_learning_resource(self, item):
        """创建LearningResource对象"""

        # 分类映射
        category_mapping = {
            'trouble': 'trouble',
            'knowledge': 'knowledge',
            'mindfulness': 'mindfulness',
            'anxiety': 'anxiety',
            'depression': 'depression',
            'stress': 'stress',
            'relationship': 'relationship',
            'sleep': 'sleep'
        }

        # 类型映射
        type_mapping = {
            'trouble': 'trouble',
            'knowledge': 'knowledge',
            'girl': 'girl',
            'boy': 'boy',
        }

        # 创建资源对象
        resource = LearningResource(
            title=item.get('title', ''),
            description=item.get('description', ''),
            content=item.get('content', ''),
            type=type_mapping.get(item.get('type', 'knowledge'), 'knowledge'),
            category=category_mapping.get(item.get('category', 'trouble'), 'trouble'),
            duration=item.get('duration', '15分钟阅读'),
            rating=float(item.get('rating', 4.5)),
            file_size=item.get('fileSize', ''),
            download_url=item.get('downloadUrl', '')
        )

        return resource

# (base) H:\python_code1\psychology_project\psychology_project>python manage.py import_learning_data


# # 如果你想要独立运行的脚本（不使用Django管理命令），可以使用以下代码：
#
# def standalone_import():
#     """独立运行的导入脚本"""
#     import django
#     from django.conf import settings
#
#     # 配置Django环境
#     if not settings.configured:
#         os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project.settings')  # 替换为你的项目设置
#         django.setup()
#
#     # 检查现有数据
#     if LearningResource.objects.exists():
#         print("数据库中已有数据，请先清空数据库或修改此脚本以允许覆盖")
#         return False
#
#     json_files = [
#         '成长的烦恼.json',
#         '青春期男孩.json',
#         '青春期女孩.json'
#     ]
#
#     imported_count = 0
#
#     # 分类和类型映射
#     category_mapping = {
#         'trouble': 'trouble',
#         'knowledge': 'knowledge',
#         'mindfulness': 'mindfulness',
#         'anxiety': 'anxiety',
#         'depression': 'depression',
#         'stress': 'stress',
#         'relationship': 'relationship',
#         'sleep': 'sleep'
#     }
#
#     type_mapping = {
#         'trouble': 'trouble',
#         'knowledge': 'knowledge',
#         'article': 'article',
#         'book': 'book'
#     }
#
#     try:
#         with transaction.atomic():
#             for json_file in json_files:
#                 file_path = os.path.join(settings.BASE_DIR, json_file)
#
#                 if not os.path.exists(file_path):
#                     print(f"文件不存在，跳过: {json_file}")
#                     continue
#
#                 print(f"正在导入: {json_file}")
#
#                 with open(file_path, 'r', encoding='utf-8') as f:
#                     data = json.load(f)
#
#                 for item in data:
#                     resource = LearningResource(
#                         title=item.get('title', ''),
#                         description=item.get('description', ''),
#                         content=item.get('content', ''),
#                         type=type_mapping.get(item.get('type', 'article'), 'article'),
#                         category=category_mapping.get(item.get('category', 'trouble'), 'trouble'),
#                         duration=item.get('duration', '15分钟阅读'),
#                         rating=float(item.get('rating', 4.5)),
#                         file_size=item.get('fileSize', ''),
#                         download_url=item.get('downloadUrl', '')
#                     )
#                     resource.save()
#                     imported_count += 1
#
#         print(f"✅ 成功导入 {imported_count} 条数据")
#         return True
#
#     except Exception as e:
#         print(f"❌ 导入失败: {str(e)}")
#         return False
#
#
# if __name__ == '__main__':
#     standalone_import()